/*
 * @Author: 杨超
 * @Date: 2021-10-29 15:12:36
 * @LastEditTime: 2021-10-29 18:02:32
 * @LastEditors: 杨超
 * @Description: 检查当前桩号是否在公路范围内
 */
import { RoadModel } from '@/models'

/**
 * 进行是否在桩号范围内验证
 * @param {*} highwayNo 公路编号
 * @param {*} direction 方向：上行1，下行2
 * @param {*} state 桩号前半部分：K9+002，为9
 * @param {*} roadStake 当前公路桩号范围，用于显示提示语
 * @param {*} dontRequired  是否是不是必填
 */
const useCheckStake = (highwayNo, direction, state, roadStake, dontRequired) => {
    const roadModel = new RoadModel()

    function validStake(rule, value, callback, highwayNo, direction, state) {
        const valid = /^[0-9]*$/.test(value)
        if (value || value === 0) {
            if (!valid) {
                callback(new Error('请输入整数'))
            } else {
                const data = {
                    highwayNo,
                    direction,
                    stakeNo: `K${state}+${value}`
                }
                roadModel
                    .checkStake(data)
                    .then(res => {
                        if (res && res.length > 0) {
                            callback()
                        } else {
                            callback(new Error(`范围：${roadStake}`))
                        }
                    })
                    .catch(() => {
                        callback(new Error('桩号格式不正确'))
                    })
            }
        } else {
            if (!dontRequired) {
                callback(new Error('请输入桩号'))
            } else {
                callback()
            }
        }
    }

    const rule = {
        validator: (rule, value, callback) => validStake(rule, value, callback, highwayNo, direction, state),
        trigger: 'blur'
    }
    return rule
}

export default useCheckStake
